package com.gk.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gk.study.Vo.CourseTeacherVO;
import com.gk.study.common.CourseStatus;
import com.gk.study.entity.Course;
import com.gk.study.entity.Score;
import com.gk.study.mapper.CourseMapper;
import com.gk.study.mapper.ScoreMapper;
import com.gk.study.service.CourseService;
import com.gk.study.service.OrderService;
import com.gk.study.service.ThingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ThingService thingService;

    @Autowired
    private ScoreMapper scoreMapper;


    @Override
    public List<Course> getCoursesByUser(Long userId, CourseStatus status) {
        LambdaQueryWrapper<Course> query = new LambdaQueryWrapper<>();
        query.eq(Course::getStudentId, userId)
                .eq(status != null, Course::getStatus, status);
        return baseMapper.selectList(query);
    }

    @Override
    @Transactional
    public void cancelCourse(Long courseId, Long userId) {
        Course course = baseMapper.selectById(courseId);
        if (course == null) throw new RuntimeException("课程不存在");
        if (!course.getStudentId().equals(userId)) throw new RuntimeException("无权操作");
        if (course.getStatus() != CourseStatus.PENDING) throw new RuntimeException("仅可取消待确认的课程");

        course.setStatus(CourseStatus.CANCELED);
        baseMapper.updateById(course);

//        // 可选：关联取消订单逻辑
//        orderService.cancelOrder(course.getOrderId());
    }

    @Override
    @Transactional
    public void completeCourse(Long courseId, Long userId) {
        Course course = baseMapper.selectById(courseId);
        if (course == null) throw new RuntimeException("课程不存在");
        if (!course.getStudentId().equals(userId)) throw new RuntimeException("无权操作");
        if (course.getStatus() != CourseStatus.PROGRESS) throw new RuntimeException("课程未在进行中");

        course.setStatus(CourseStatus.COMPLETED);
        baseMapper.updateById(course);
    }


    @Override
    public List<CourseTeacherVO> getTeacherCourses(Long teacherId, CourseStatus status) {
        String statusValue = (status != null) ? status.getValue() : null;
        return baseMapper.selectTeacherCourses(teacherId, statusValue);
    }

    @Override
    public List<Course> getUnratedCompletedCourses(Long userId) {
        // 获取用户已完成的课程
        List<Course> completedCourses = this.getCoursesByUser(userId, CourseStatus.COMPLETED);

        // 过滤未评价的课程
        return completedCourses.stream()
                .filter(course -> !scoreMapper.existsByCourseAndUser(course.getId(), userId))
                .collect(Collectors.toList());
    }

    @Transactional
    @Override
    public void submitEvaluation(Score score) {
        // 获取课程信息
        Course course = this.getById(score.getCourseId());
        if (course == null) {
            throw new RuntimeException("课程不存在");
        }

        // 设置教师ID
        score.setTeacherId(course.getTeacherId()); // 关键修改

        // 后续验证和保存逻辑保持不变
        if (!course.getStatus().equals(CourseStatus.COMPLETED)) {
            throw new RuntimeException("课程未完成");
        }
        if (!course.getStudentId().equals(score.getUserId())) {
            throw new RuntimeException("无权评价该课程");
        }
        if (scoreMapper.existsByCourseAndUser(score.getCourseId(), score.getUserId())) {
            throw new RuntimeException("请勿重复评价");
        }

        score.setCreateTime(LocalDateTime.now());
        scoreMapper.insert(score); // 此时SQL包含teacher_id字段
    }




}